<?php
require_once dirname(__FILE__) . '/../../bootstrap.unit.php';
require_once FORAGE_APP_PATH . '/util/Profiler.php';

class ForageProfilerTest extends ForageUnitTestCase
{
  private $profiler;

  public function setUp()
  {
    $this->profiler = new ForageProfiler();
  }

  public function tearDown()
  {
    unset($this->profiler);
  }

  public function runSimpleProfile()
  {
    for ($i=0; $i<10; $i++) {
      $this->profiler->start('name');
      usleep(10000);
      $this->profiler->stop('name');
    }
  }

  public function testObjectDefaults()
  {
    $this->assertEquals(0, $this->profiler->total('any'));
    $this->assertEquals(0, $this->profiler->average('any'));
    $this->assertEquals(0, $this->profiler->hits('any'));
    $this->assertEquals(0, $this->profiler->rate('any'));
  }
  
  public function testProfilingTotalTimeSpent()
  {
    $this->runSimpleProfile();
    $total = $this->profiler->total('name');
    $this->assertWithinMargin($total, 0.1, 0.08);
  }

  public function testProfilingAverageTimeSpent()
  {
    $this->runSimpleProfile();
    $average = $this->profiler->average('name');
    $this->assertWithinMargin($average, 0.01, 0.008);
  }

  public function testProfilingHitCount()
  {
    $this->runSimpleProfile();
    $hits = $this->profiler->hits('name');
    $this->assertEquals($hits, 10);
  }

  public function testProfilingRate()
  {
    $this->runSimpleProfile();
    $rate = $this->profiler->rate('name');
    $this->assertWithinMargin($rate, 100, 40);
  }

  /**
   * @expectedException ForageProfilerException
   */
  public function testStopFailsIfNotStarted()
  {
    $this->profiler->stop('name');
  }
}
